package fr.labri.macchiato.framework.business.encoder;

import java.util.ArrayList;
import java.util.List;

import org.fusesource.restygwt.client.JsonEncoderDecoder;

import com.google.gwt.core.client.GWT;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.smartgwt.client.util.JSON;

import fr.labri.macchiato.framework.business.model.businessEntity.BusinessEntity;
import fr.labri.macchiato.framework.business.model.product.Model;
import fr.labri.macchiato.framework.business.model.product.Offer;
import fr.labri.macchiato.framework.business.model.product.ProductFactory;
import fr.labri.macchiato.framework.technical.encoder.EncoderGeneric;

/**
 * Encoder for the {@link Offer} class
 * 
 * @author Matthieu FOUCAULT
 * 
 */
class OfferEncoder extends EncoderGeneric<Offer> {

	interface OfferCodec extends JsonEncoderDecoder<Offer> {
	}

	OfferEncoder() {
		codec = GWT.create(OfferCodec.class);
	}

	@Override
	public List<Offer> decodeSparqlResult(String jsonString) {

		List<Offer> offers = new ArrayList<Offer>();

		JSONObject result = new JSONObject(JSON.decode(jsonString));
		result = result.get("results").isObject();

		JSONArray bindings = result.get("bindings").isArray();
		for (int i = 0; i < bindings.size(); i++) {
			
			String ean = getAsString(bindings, i, "ean");
			String name = getAsString(bindings, i, "name");
			String priceString = getAsString(bindings, i, "price");
			double price = Double.valueOf(priceString);
			String providerName = getAsString(bindings, i, "provider");

			BusinessEntity provider = new BusinessEntity(providerName);
			Model model = ProductFactory.newModel(ean, name);
			Offer offer = ProductFactory.newOffer(model, provider, price);

			offers.add(offer);
		}
		return offers;
	}

}
